package com.hdax.gulimall.order.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.hdax.gulimall.order.service.OrderService;
import com.hdax.gulimall.order.vo.OrderConfirmVo;
import com.hdax.gulimall.order.vo.OrderSubmitVo;
import com.hdax.gulimall.order.vo.SubmitResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebControlller {

    @Autowired
    private OrderService orderService;


    /**
     * 订单确认页需要返回的 数据
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
     public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo=orderService.confirmOrder();
        model.addAttribute("confirmOrderData",orderConfirmVo);
        return "confirm";
     }

    /**
     * 提交订单
     * attrid
     * 令牌
     * 价格
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) throws JsonProcessingException {
        //创建订单
        SubmitResponseVo submitResponseVo=orderService.submitOrder(orderSubmitVo);
        if(submitResponseVo.getCode()==0){
            model.addAttribute("submitOrderResp",submitResponseVo);
            return "pay";
        }else{
            //下单失败回到订单确认页，重新确认订单
            String msg="下单失败";
            switch (submitResponseVo.getCode()){
                case 1: msg+="令牌校验失败";
                break;
                case 2: msg+="订单商品的价格发生改变";
                break;
                case 3: msg+="库存锁定失败，商品库存不足";
                break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
     }
}
